package org.liukai.ssh_ems.util;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.Test;
import org.liukai.ssh_ems.entity.po.Emp;

import java.util.List;

/**
 * @project ssh_ems
 * @create HibernateUtil.java 
 * 
 * @author liukai
 * @date 2016/1/12 11:20
 * @detail 
 */
//session方法实现crud 暂时没用  使用的spring提供的HibernaTetemplate
public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // create SessionFactory from hibernate.cfg.xml  默认加载是properties文件  所以在后面加上.configure()方法
            Configuration configuration = new Configuration().configure();
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
            return new Configuration().configure().buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        //System.out.println("test");
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }

    @Test
    public void test() {
        Session session = getSessionFactory().openSession();
        Query q = session.createQuery("from Emp ");
        System.out.println("--------------------------------------------------");
        List<Emp> list = q.list();
        for (Emp e : list) {
            System.out.println(e);
        }

        /*Emp emp = new Emp();
        emp.setAge(18);
        emp.setMarry(false);
        emp.setName("liu");
        emp.setSal(13.3);
        Session session = getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        try {
            session.save(emp);
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            session.close();
        }*/

        /*Session session = getSessionFactory().openSession();
        Emp emp = (Emp)session.get(Emp.class, 13);
        emp.setAge(20);
        emp.setMarry(false);
        emp.setName("kai");
        emp.setSal(13.3);
        Transaction tx = session.beginTransaction();
        try {
            session.update(emp);
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            session.close();
        }*/

    }
}
